package com.macro.mall.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 应用事件监听器
 * 监听应用启动、就绪和关闭事件，记录关键状态信息
 * 
 * @author mall
 * @since 1.0
 */
@Component
public class ApplicationEventListener {

    private static final Logger logger = LoggerFactory.getLogger(ApplicationEventListener.class);
    private static final Logger healthLogger = LoggerFactory.getLogger("HEALTH");

    @Autowired
    private MonitoringConfig.ApplicationStartupMonitor startupMonitor;

    /**
     * 应用启动事件监听
     */
    @EventListener
    public void handleApplicationStarted(ApplicationStartedEvent event) {
        logger.info("应用启动事件触发: {}", LocalDateTime.now());
        healthLogger.info("应用状态: STARTED");
        
        // 记录启动环境信息
        String[] activeProfiles = event.getApplicationContext().getEnvironment().getActiveProfiles();
        logger.info("激活的配置文件: {}", String.join(",", activeProfiles));
        
        // 记录JVM信息
        Runtime runtime = Runtime.getRuntime();
        logger.info("JVM信息 - 最大内存: {}MB, 总内存: {}MB, 空闲内存: {}MB", 
            runtime.maxMemory() / 1024 / 1024,
            runtime.totalMemory() / 1024 / 1024,
            runtime.freeMemory() / 1024 / 1024);
    }

    /**
     * 应用就绪事件监听
     */
    @EventListener
    public void handleApplicationReady(ApplicationReadyEvent event) {
        logger.info("应用就绪事件触发: {}", LocalDateTime.now());
        healthLogger.info("应用状态: READY");
        
        // 记录启动完成信息
        startupMonitor.logStartupComplete();
        
        // 记录重要端点信息
        String port = event.getApplicationContext().getEnvironment().getProperty("server.port", "8080");
        logger.info("=== 重要端点信息 ===");
        logger.info("健康检查: http://localhost:{}/actuator/health", port);
        logger.info("应用信息: http://localhost:{}/actuator/info", port);
        logger.info("指标监控: http://localhost:{}/actuator/metrics", port);
        logger.info("Swagger文档: http://localhost:{}/swagger-ui/", port);
        
        // 记录数据库和Redis连接状态
        try {
            logger.info("开始验证外部依赖连接状态...");
            healthLogger.info("外部依赖检查: 开始验证数据库和Redis连接");
        } catch (Exception e) {
            logger.error("外部依赖检查失败: {}", e.getMessage());
            healthLogger.error("外部依赖检查: 失败 - {}", e.getMessage());
        }
        
        logger.info("=== Mall-Admin 应用完全就绪，可以接收请求 ===");
    }

    /**
     * 应用关闭事件监听
     */
    @EventListener
    public void handleContextClosed(ContextClosedEvent event) {
        logger.info("应用关闭事件触发: {}", LocalDateTime.now());
        healthLogger.info("应用状态: SHUTTING_DOWN");
        
        logger.info("=== Mall-Admin 应用开始关闭 ===");
        logger.info("正在清理资源...");
        
        // 记录关闭时的运行时信息
        Runtime runtime = Runtime.getRuntime();
        logger.info("关闭时JVM信息 - 使用内存: {}MB, 最大内存: {}MB", 
            (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024,
            runtime.maxMemory() / 1024 / 1024);
        
        logger.info("=== Mall-Admin 应用关闭完成 ===");
        healthLogger.info("应用状态: SHUTDOWN");
    }
}